package cn.niitcxl.controller;

import cn.niitcxl.domain.adminUser;
import cn.niitcxl.services.LoginServices;
import cn.niitcxl.utils.R;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户登录的controller
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LoginServices loginServices;

    /**
     * 用户登录的方法
     * @param Admin
     * @param session
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping
    public R login(@RequestBody(required = true) adminUser Admin, HttpSession session, HttpServletResponse response) throws IOException {
        if (Admin!=null){
            //获取用户名
            String username = Admin.getUsername();
            //获取密码
            String password = Admin.getPassword();
            //判断用户名或者密码是否为空
            if (Strings.isNotEmpty(username)&&Strings.isNotEmpty(password)){
                adminUser adminUser = loginServices.login(username, password);
                session.setAttribute("userAdmin",adminUser);
                if (adminUser!=null){
                    //登录成功跳转到 管理员页面
                    return new R().ok().data("user",adminUser);
                }
            }

        }

        return new R().error().message("不知道密码!不要乱登录...去问网站管理员");
    }

    /**
     * 退出登录的方法
     * @param session
     * @return
     */
    @DeleteMapping
    public R exitLogin(HttpSession session){
        session.removeAttribute("userAdmin");
        return new R().ok().message("退出登录成功!");
    }

}